package com.dvt.faceScan;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.provider.SyncStateContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dvt.faceScan.httpUntil.XmlRpcUtils;
import com.dvt.faceScan.httpUntil.requestThread;
import com.dvt.faceScan.widget.Config;

import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Created by XGJ on 2018/3/26.
 */

public class LoginActivity extends Activity implements View.OnClickListener {
    //声明变量
    private Handler mHandler;
    EditText account;
    EditText password;
    EditText ip;
    private Button loginButton;
    private CheckBox mAutoSavePassword;
    private TextView setView;
    private ImageView ipView;
    final Context context = this;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        mAutoSavePassword = (CheckBox) findViewById(R.id.auto_save_password);
        account = (EditText) findViewById(R.id.login_user);
        password = (EditText) findViewById(R.id.login_password);
        //检查是否记住密码
        final SharePreferenceUtil util = new SharePreferenceUtil(
                LoginActivity.this, "");
        if ("1".equals(util.getRemberFlag())) {
            mAutoSavePassword.setChecked(true);
            account.setText(util.getAccount());
            password.setText(util.getPasswd());
        }else{
            mAutoSavePassword.setChecked(false);
        }
        //自动设置IP端口
        Config.baseURL = "http://" + util.getIp() + ":" + util.getPort();

        loginButton = (Button) findViewById(R.id.login);
        setView = (TextView) findViewById(R.id.Tv_set);
        ipView = (ImageView) findViewById(R.id.Iv_ip);
        loginButton.setOnClickListener(this);
        setView.setOnClickListener(this);
        ipView.setOnClickListener(this);
        account.requestFocus();
        account.setSelection(account.getText().length());

        mAutoSavePassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if(isChecked){
                    util.setRemberFlag("1");
                }else{
                    util.setRemberFlag("0");
                }
            }
        });
    }

    public void onClick(View v) {
        // 根据id判断单击的是哪个控件，固定写法
        switch (v.getId()) {
            case R.id.login:
                //登录
                login();
                break;
            case R.id.Tv_set:
                //设置
                setting();
                break;
            case R.id.Iv_ip:
                //设置
                setting();
                break;
            default:
                break;
        }
    }

    public void setting() {
        //弹出设置IP端口框
        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.prompts, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);

        alertDialogBuilder.setView(promptsView);
        SharePreferenceUtil util = new SharePreferenceUtil(
                LoginActivity.this, "");

        final EditText userInput = (EditText) promptsView
                .findViewById(R.id.editTextDialogIpInput);
        userInput.setText(util.getIp());
        userInput.requestFocus();
        userInput.setSelection(util.getIp().length());
        final EditText portInput = (EditText) promptsView
                .findViewById(R.id.editTextDialogPortInput);
        portInput.setText(util.getPort());
        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton(R.string.commit,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                SharePreferenceUtil util = new SharePreferenceUtil(
                                        LoginActivity.this, "");
                                util.setIp(userInput.getText().toString());
                                util.setPort(portInput.getText().toString());
                                Config.baseURL = "http://" + util.getIp() + ":" + util.getPort();
                            }
                        })
                .setNegativeButton(R.string.cancle,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }

    private void login() {
        if (account.getText().length() != 0 || password.getText().length() != 0) {
            Config.account = account.getText().toString();
            Config.password = password.getText().toString();
            SharePreferenceUtil util = new SharePreferenceUtil(
                    LoginActivity.this, "");
            util.setAccount(account.getText().toString());
            util.setPasswd(password.getText().toString());

            requestLogin(); //调用登录方法
        } else {
            if (account.getText().toString().trim().equals("")) {
                Toast.makeText(this, getString(R.string.accountName_empty),
                        Toast.LENGTH_SHORT).show();
            } else if (password.getText().toString().trim().equals("")) {
                Toast.makeText(this, getString(R.string.password_empty),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    //获取登录接口返回值
    private void requestLogin() {
        requestThread rThread = new requestThread();
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(rThread);
        try {
            String request_login = future.get(5000, TimeUnit.SECONDS);
            Config.UID = Integer.valueOf(request_login).intValue(); //String转int
            if (Config.UID == 1) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(this, getString(R.string.loginText),
                        Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
